import sys
from PyQt5 import QtWidgets,QtCore,QtGui
from PyQt5.QtCore import Qt
# from custom.stackedWidget import StackedWidget
# from custom.treeView import FileSystemTreeView
# from custom.listWidgets import FuncListWidget, UsedListWidget
# from custom.graphicsView import GraphicsView
# from pyqtconsole.console import PythonConsole
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui
pgw=None
def linear_regression(x,y):
    N = len(x)
    sumx = sum(x)
    sumy = sum(y)
    sumx2 = sum(x**2)
    sumxy = sum(x*y)
    A = np.mat([[N,sumx],[sumx,sumx2]])
    b = np.array([sumy,sumxy])

    return np.linalg.solve(A,b)
# 生成系数矩阵A
def gen_coefficient_matrix(X):
    N = len(X)
    m = 3
    A = []
 # 计算每一个方程的系数
    for i in range(m):
        a = []
  # 计算当前方程中的每一个系数
        for j in range(m):
            a.append(sum(X ** (i+j)))
        A.append(a)
    return A

# 计算方程组的右端向量b
def gen_right_vector(X, Y):
    N=len(X)
    m=3
    b=[]
    for i in range(m):
        b.append(sum(X**i*Y))
    return b

def pgWidget():
    global pgw
    pg.setConfigOptions(imageAxisOrder='row-major')
    win = pg.GraphicsLayoutWidget()
    win.setWindowTitle('pyqtgraph example: Image Analysis')
    # A plot area (ViewBox + axes) for displaying the image
    plt = win.addPlot(title="")#plot item
    print(plt)
    x = np.arange(0,5,0.1)
    # z = [3+5*x for x in x]
    z = [2+3*x+4*x**2 for x in x]
    y = np.array([np.random.normal(z,3) for z in z])
    #y = [np.random.normal(z,1) for z in z]
    #a0,a1 = linear_regression(x,y)
    A = gen_coefficient_matrix(x)
    b = gen_right_vector(x,y)

    a0, a1, a2 = np.linalg.solve(A, b)    

    # _y = [a0 + a1*x for x in x]
    _y = np.array([a0 + a1*x + a2*x**2 for x in x])
    #设置显示中文
    # plt.rcParams['font.family'] = 'SimHei'
    #绘图标题
    # plt.title("这里时标题",fontsize = 20)
    # plt.xlabel("这里是x轴",fontsize=14)
    # plt.ylabel("这里是y轴",fontsize=14)

    plt.plot(x,y,symbol="o")
    plt.plot(x,_y,pen=pg.mkPen(color="r", width=2), style=Qt.DashLine)
    # #这是图例
    # plt.legend(prop = {"family":"Times New Roman","size":14})
    # #plt.savefig()   #输出图像
    # plt.show()

    # ptx=[1,2,3]
    # pty=[4,5,6]
    # p1.plot(x=ptx, y=pty, pen=None, symbol='o')
    # ptx=[.1,.2,.3]
    # pty=[.4,.5,.6]
    # p1.plot(x=ptx, y=pty, pen=None, symbol='o')
    pgw=plt
    return win
def mainW():
    w=QtWidgets.QWidget()
    main_layout = QtWidgets.QVBoxLayout(w)
    main_layout.addWidget(pgWidget())
    b=QtWidgets.QPushButton("draw")
    b.clicked.connect(b_click)
    main_layout.addWidget(b)
    w.setLayout(main_layout)
    return w
def b_click():
    pgw.clear()
if __name__ == "__main__":
    from getpath import getpath
    import os
    import logging
    from logging.handlers import RotatingFileHandler
    from PyQt5 import QtWidgets
    handlers=[RotatingFileHandler(filename="cv.log", maxBytes=10*1024*1024,backupCount=3),# logging.FileHandler(initpath+'/myapp.log'),
            logging.StreamHandler(sys.stdout)
    ]
    # handlers=[logging.StreamHandler(sys.stdout)]
    logging.basicConfig(level=logging.DEBUG,
                        format = '%(asctime)s - %(name)s - %(levelname)s -%(funcName)s - %(message)s',
                        handlers=handlers)
    logging.info('begin')
    app = QtWidgets.QApplication(sys.argv)
    # window = pgWidget()
    window=mainW()
    window.show()
    sys.exit(app.exec())
